<!-- pages/login/components/mobile.vue -->
<script setup>
import { getCodeApi, loginByMobileApi } from '@/apis/user';
import { useUserStore } from '@/stores/user';
import { ref } from 'vue';

const showCountDown = ref(false)
const formRef = ref(null)
const isAgree = ref(false)
const userStore = useUserStore()

const getMobileCode = async () => {
  try{
    await formRef.value.validateField(['mobile'])
    const data = await getCodeApi({mobile:formData.value.mobile,type:'login'})
    uni.showToast({
      title:'获取验证码成功！',
      icon:'success'
    })
    // 显示倒计时
    showCountDown.value = true
    formData.value.code = data.code
  }catch(e){
    console.log(e);
    
  }
 
}
// 表单数据
const formData = ref({
  mobile: '13230000023',
  code: ''
})

// 验证表单数据规则
const formRules = {
  mobile: {
    rules: [
      { required: true, errorMessage: '请填写手机号码' },
      { pattern: '^1\\d{10}$', errorMessage: '手机号码格式不正确' },
    ]
  },
  code:{
    rules: [
        { required: true, errorMessage: '请输入验证码' },
        { pattern: '^\\d{6}$', errorMessage: '验证码格式不正确' },
      ],
  }
}

// 登录方法
const onFormSubmit = async()=>{
  try{
    // 表单验证
    await formRef.value.validate()
    if(!isAgree.value) return uni.showToast({ title: '请勾选同意用户协议', icon: 'none' })
    // 调用接口
  const res = await loginByMobileApi(formData.value)
  // 存储token
  userStore.token = res.token

  //页面跳转
  uni.switchTab({
    url:'/pages/my/index'
  })
  
  }catch(e){
    console.log(e);
    
  }
}
</script>

<template>
  <uni-forms class="login-form" :rules="formRules" :model="formData" ref="formRef">
    <uni-forms-item name="mobile">
      <uni-easyinput :input-border="false" :clearable="false" placeholder="请输入手机号" placeholder-style="color: #C3C3C5"
        v-model="formData.mobile" />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput :input-border="false" :clearable="false" placeholder="请输入验证码" placeholder-style="color: #C3C3C5"
        v-model="formData.code" />
      <text class="text-button" v-if="!showCountDown" @click="getMobileCode">获取验证码</text>
      <view class="text-button" v-else>
        <uni-countdown :show-day="false" :show-hour="false" :show-minute="false" :second="59"
          @timeup="showCountDown = false" />秒后重新发送
      </view>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" color="#16C2A3" @click="isAgree=!isAgree"/>
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onFormSubmit">登 录</button>
  </uni-forms>
</template>

<script>
export default {
  options: {
    styleIsolation: 'shared',
  },
}
</script>

<style lang="scss">
@import './styles.scss';
</style>